import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:largefriends/service/manager/lf_store_helper.dart';

mixin KeyboardHeight<T extends StatefulWidget>
    on State<T>, WidgetsBindingObserver {
  final WidgetsBinding _widgetsBinding = WidgetsBinding.instance;

  Timer? _timer;
  double defaultHeight = LfStorageManager.getDouble('key_keyboard_height') ?? 0;

  @override
  void initState() {
    _widgetsBinding.addObserver(this);
    super.initState();
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    final viewInsets = EdgeInsets.fromViewPadding(
        View.of(context).viewInsets, View.of(context).devicePixelRatio);
    keyboardHeight(viewInsets.bottom);
    try {
      if (_timer != null) {
        _timer?.cancel();
      }
    } catch (e) {}

    _timer = Timer(const Duration(milliseconds: 40), () {
      var height = viewInsets.bottom;
      if (height > defaultHeight) {
        defaultHeight = height;
        LfStorageManager.setDouble('key_keyboard_height', height);
      }
    });
  }

  void keyboardHeight(double height) {}

  @override
  void dispose() {
    try {
      if (_timer != null) {
        _timer?.cancel();
        _timer = null;
      }
    } catch (e) {}
    _widgetsBinding.removeObserver(this);
    super.dispose();
  }
}
